import 'dart:async';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../../API/user/user.dart';

class UpdatePasswordController extends GetxController {
  // 状态管理变量
  RxBool showPassword1 = false.obs;
  RxBool showPassword2 = false.obs;
  RxString oldPassword = ''.obs;
  RxString newPassword = ''.obs;
  RxString rePassword = ''.obs;
  // 注册逻辑
  Future<void> updatePassword() async {
    if (validateForm()) {
      // if (kDebugMode) {
      //   print(
      //     'oldPassword=${oldPassword.value} \n newPassword=${newPassword.value} \n rePassword=${rePassword.value}',
      //   );
      // }
      final response = await ApiService.updatePassword(
        oldPassword: oldPassword.value,
        newPassword: newPassword.value,
        rePassword: rePassword.value,
      );

      if (response["code"] == 20031) {
        Get.back();
        Get.snackbar("成功", "修改密码成功", snackPosition: SnackPosition.TOP);
      } else {
        Get.snackbar(
          "错误",
          "修改密码失败: ${response['message']}",
          duration: const Duration(seconds: 5),
        );
      }
    }
  }

  // 表单验证
  bool validateForm() {
    if (oldPassword.value.isEmpty || oldPassword.value.length < 6) {
      Get.snackbar("错误", "旧密码最少六个字符");
      return false;
    }
    if (newPassword.value.isEmpty || newPassword.value.length < 6) {
      Get.snackbar("错误", "新密码最少六个字符");
      return false;
    }
    if (rePassword.value.isEmpty || rePassword.value != newPassword.value) {
      Get.snackbar("错误", "两次密码不一致");
      return false;
    }
    return true;
  }
}

class UpdatePasswordPage extends StatelessWidget {
  const UpdatePasswordPage({super.key});

  @override
  Widget build(BuildContext context) {
    final UpdatePasswordController controller = Get.put(
      UpdatePasswordController(),
    );
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Color(0xFF0088FF),
        title: const Text("修改密码", style: TextStyle(color: Colors.white)),
        leading: IconButton(
          icon: const Icon(Icons.arrow_back, color: Colors.white),
          onPressed: () {
            Get.back();
          },
        ),
      ),
      body: Container(
        decoration: const BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [Color(0xFF0088FF), Colors.cyanAccent],
          ),
        ),
        child: ListView(
          padding: EdgeInsets.all(45),
          children: [
            _buildOldPasswordField(controller),
            const SizedBox(height: 40),
            _buildPasswordField(controller, isConfirm: false),
            const SizedBox(height: 40),
            _buildPasswordField(controller, isConfirm: true),
            const SizedBox(height: 40),
            ElevatedButton(
              style: ElevatedButton.styleFrom(
                backgroundColor: Colors.white,
                foregroundColor: Colors.blue,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(20),
                ),
                padding: const EdgeInsets.symmetric(horizontal: 80),
              ),
              onPressed: controller.updatePassword,
              child: const Text('确认修改'),
            ),
          ],
        ),
      ),
    );
  }
}

Widget _buildOldPasswordField(UpdatePasswordController controller) {
  return TextFormField(
    decoration: InputDecoration(
      labelText: '旧密码',
      hintText: '请输入旧密码',
      labelStyle: const TextStyle(color: Colors.white),
      hintStyle: const TextStyle(color: Colors.white),
      enabledBorder: const UnderlineInputBorder(
        borderSide: BorderSide(color: Colors.white),
      ),
      focusedBorder: const UnderlineInputBorder(
        borderSide: BorderSide(color: Colors.white),
      ),
    ),
    style: const TextStyle(color: Colors.white),
    onChanged: (value) {
      controller.oldPassword.value = value;
    },
  );
}

Widget _buildPasswordField(
  UpdatePasswordController controller, {
  required bool isConfirm,
}) {
  return Obx(
    () => TextFormField(
      decoration: InputDecoration(
        labelText: isConfirm ? '确认新密码' : '新密码',
        hintText: isConfirm ? '请确认新密码' : '请输入新密码',
        labelStyle: const TextStyle(color: Colors.white),
        hintStyle: const TextStyle(color: Colors.white),
        suffixIcon: IconButton(
          icon: Icon(
            (isConfirm
                    ? controller.showPassword2.value
                    : controller.showPassword1.value)
                ? Icons.visibility_off
                : Icons.visibility,
            color: Colors.white,
          ),
          onPressed:
              (isConfirm
                  ? controller.showPassword2.toggle
                  : controller.showPassword1.toggle),
        ),
        enabledBorder: const UnderlineInputBorder(
          borderSide: BorderSide(color: Colors.white),
        ),
        focusedBorder: const UnderlineInputBorder(
          borderSide: BorderSide(color: Colors.white),
        ),
      ),
      style: const TextStyle(color: Colors.white),
      obscureText:
          isConfirm
              ? !controller.showPassword2.value
              : !controller.showPassword1.value,
      onChanged: (value) {
        if (isConfirm) {
          controller.rePassword.value = value;
        } else {
          controller.newPassword.value = value;
        }
      },
    ),
  );
}
